//
//  DragView.m
//  pictureTouchAction
//
//  Created by 李勇 on 2018/8/11.
//  Copyright © 2018 李勇. All rights reserved.
//

#import "DragView.h"

@implementation DragView
{
    CGPoint startLocation;
}

- (instancetype)initWithImage:(UIImage *)anImage
{
    self = [super initWithImage:anImage];
    if (self)
    {
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    // Calculate and store offset, and pop view into front if needed
    startLocation = [[touches anyObject] locationInView:self];
    NSLog(@"startLocation:%f %f",startLocation.x,startLocation.y);
    [self.superview bringSubviewToFront:self];
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    // Calculate offset
    CGPoint pt = [[touches anyObject] locationInView:self];
    NSLog(@"touchesMoved:%f %f",pt.x,pt.y);

    float dx = pt.x - startLocation.x;
    float dy = pt.y - startLocation.y;
    NSLog(@"dx:%f dy %f",dx,dy);

    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    // Set new location
    self.center = newcenter;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    startLocation = [[touches anyObject] locationInView:self];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    startLocation = [[touches anyObject] locationInView:self];
}

@end
